﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using AplicacionMVC.Models;
using System.Text;


namespace AplicacionMVC.Controllers
{
    public class ReservaController : Controller
    {

        //
        // GET: /Reserva/  

        private string resRESTService = "http://localhost:1178/Reservas.svc/Reservas";
        JavaScriptSerializer js = new JavaScriptSerializer();
        SOAPServices.Dominio.Usuario usu = new SOAPServices.Dominio.Usuario();

        public SOAPServices.Dominio.Usuario obtenerusuario()
        {

            usu.Codigo = 1;
            usu.Nombre = "Renzo";
            usu.Cargo = "Analista";
            usu.Estado = '1';
            Session["usuario"] = usu;
            return usu;
        }

        //
        // GET: /Reserva/
        public ActionResult Index()
        {
            Session["reserva"] = "";
            string codusu = "1";
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(resRESTService + "/ListarReservas/" + codusu);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string resJson = reader2.ReadToEnd();
            List<ReservaAdic> resJson2 = js.Deserialize<List<ReservaAdic>>(resJson);
            return View(resJson2);
        }

        // GET: /Reserva/Create
        public ActionResult Create()
        {
            Session["reserva"] = "";
            TempData["Salas"] = ListarComboSala();
            TempData["Dias"] = ListarComboDia();
            TempData["Turnos"] = ListarComboTurno();
            return View();
        }

        private ICollection<SelectListItem> ListarComboSala()
        {
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:1178/Salas.svc/Salas");
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string salaJson = reader2.ReadToEnd();
            List<Sala> sala = js.Deserialize<List<Sala>>(salaJson);

            ICollection<SelectListItem> tipos = new List<SelectListItem>();
            tipos.Add(new SelectListItem() { Value = string.Empty, Text = "Seleccione Sala" });

            foreach (Sala salas in sala)
                tipos.Add(new SelectListItem()
                {
                    Value = salas.Id_sala.ToString(),
                    Text = salas.Nombre

                });
            return tipos;
        }

        private ICollection<SelectListItem> ListarComboSala1()
        {
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:1178/Salas.svc/Salas");
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string salaJson = reader2.ReadToEnd();
            List<Sala> sala = js.Deserialize<List<Sala>>(salaJson);

            ICollection<SelectListItem> tipos = new List<SelectListItem>();
            tipos.Add(new SelectListItem() { Value = string.Empty, Text = "Seleccione Sala" });

            foreach (Sala salas in sala)
                tipos.Add(new SelectListItem()
                {
                    Value = salas.Nombre,
                    Text = salas.Nombre

                });
            return tipos;
        }

        private IEnumerable<SelectListItem> ListarComboDia()
        {
            IEnumerable<SelectListItem> lista = new SelectList(

                new[]
                {
                    new SelectListItem{ Value = "dia", Text = "Selecccione su dia" },
                    new SelectListItem{ Value = "Lunes", Text = "Lunes" },
                    new SelectListItem{ Value = "Martes", Text = "Martes" },
                    new SelectListItem{ Value = "Miercoles", Text = "Miercoles" },
                    new SelectListItem{ Value = "Jueves", Text = "Jueves" },
                    new SelectListItem{ Value = "Viernes", Text = "Viernes" },
                    new SelectListItem{ Value = "Sabado", Text = "Sabado" }
                }, "Value", "Text");

            return lista;
        }

        private IEnumerable<SelectListItem> ListarComboTurno()
        {

            IEnumerable<SelectListItem> lista = new SelectList(

                new[]
                {
                    new SelectListItem{ Value = "turno", Text = "Selecccione su turno" },
                    new SelectListItem{ Value = "Mañana", Text = "Mañana" },
                    new SelectListItem{ Value = "Tarde", Text = "Tarde" },
                    new SelectListItem{ Value = "Noche", Text = "Noche" }
                }, "Value", "Text");

            return lista;
        }

        private int idSala(string nombre)
        {

            string salaRESTService1 = "http://localhost:1178/Salas.svc/Sala";
            HttpWebRequest req3 = (HttpWebRequest)WebRequest.Create(salaRESTService1 + "/" + nombre);
            req3.Method = "GET";
            HttpWebResponse res3 = (HttpWebResponse)req3.GetResponse();
            StreamReader reader3 = new StreamReader(res3.GetResponseStream());
            string salaJson3 = reader3.ReadToEnd();
            Sala sala1 = js.Deserialize<Sala>(salaJson3);

            return sala1.Id_sala;
        }

        // POST: /Reserva/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            usu = (SOAPServices.Dominio.Usuario)Session["usuario"];
            int codusu = 1;
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(resRESTService + "/Listar/" + codusu);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string resJson = reader2.ReadToEnd();
            List<Reserva> reser1 = js.Deserialize<List<Reserva>>(resJson);
            ReservaAdic reser2 = new ReservaAdic();

            if (reser1 != null)
            {

                reser2.sala = collection["Sala"];
                reser2.dia = collection["Dia"];
                reser2.turno = collection["Turno"];
                reser2.observacion = collection["observacion"];
                TempData["Salas"] = ListarComboSala();
                TempData["Dias"] = ListarComboDia();
                TempData["Turnos"] = ListarComboTurno();

                for (int i = 0; i < reser1.Count; i++)
                {
                    if (reser1[i].id_sala == int.Parse(reser2.sala) & reser1[i].dia == reser2.dia & reser1[i].turno == reser2.turno)
                    {
                        Session["reserva"] = "Reserva ya creada el dia " + reser2.dia + " en el turno " + reser2.turno;
                        return View(reser2);
                    }
                }

            }

            try
            {
                string postdata = "{\"id_usuario\":\"" + codusu + "\",\"id_sala\":\"" + int.Parse(collection["Sala"]) + "\",\"dia\":\"" + collection["Dia"] + "\",\"turno\":\"" + collection["Turno"] + "\",\"observacion\":\"" + collection["observacion"] + "\",\"estado\":\"1\"}";

                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resRESTService + "/CrearRes");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();

                HttpWebRequest reqt = (HttpWebRequest)WebRequest.Create(resRESTService + "/Enviar");
                reqt.Method = "POST";
                reqt.ContentLength = data.Length;
                reqt.ContentType = "application/json";
                var reqStream1 = reqt.GetRequestStream();
                reqStream1.Write(data, 0, data.Length);
                var res1 = (HttpWebResponse)reqt.GetResponse();
                StreamReader reader3 = new StreamReader(res.GetResponseStream());
                string alumnoJson3 = reader3.ReadToEnd();
                JavaScriptSerializer js3 = new JavaScriptSerializer();
                Reserva alumnoModificado = js3.Deserialize<Reserva>(alumnoJson3);

                return RedirectToAction("Index");

            }
            catch (Exception e)
            {
                ModelState.AddModelError("Error", e.Message);
                return View();


            }

            return RedirectToAction("Index");
        }

        // GET: /Sede/Details/5
        public ActionResult Details(string id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resRESTService + "/ObtenerRes/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string salaJson = reader.ReadToEnd();
            ReservaAdic rese = js.Deserialize<ReservaAdic>(salaJson);
            return View(rese);
        }

        public ActionResult Delete(string id, FormCollection collection)
        {
            try
            {
                string postdata = "\"" + id + "\"";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resRESTService);
                req.Method = "DELETE";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Error", e.Message);
                return View();
            }
        }


        public ActionResult Edit(string id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resRESTService + "/ObtenerRes/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string salaJson = reader.ReadToEnd();
            ReservaAdic resAd = js.Deserialize<ReservaAdic>(salaJson);
            //Session["data"] = "";


            TempData["Salas"] = ListarComboSala1();
            TempData["Dias"] = ListarComboDia();
            TempData["Turnos"] = ListarComboTurno();
            return View(resAd);
        }

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {

            usu = (SOAPServices.Dominio.Usuario)Session["usuario"];
            int codusu = 1;
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(resRESTService + "/ListarReservas/" + codusu);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string resJson = reader2.ReadToEnd();
            List<ReservaAdic> reser1 = js.Deserialize<List<ReservaAdic>>(resJson);
            ReservaAdic reser2 = new ReservaAdic();

            if (reser1 != null)
            {

                reser2.sala = collection["Sala"];
                reser2.dia = collection["Dia"];
                reser2.turno = collection["Turno"];
                reser2.observacion = collection["observacion"];
                TempData["Salas"] = ListarComboSala1();
                TempData["Dias"] = ListarComboDia();
                TempData["Turnos"] = ListarComboTurno();

                for (int i = 0; i < reser1.Count; i++)
                {
                    if (reser1[i].sala == reser2.sala & reser1[i].dia == reser2.dia & reser1[i].turno == reser2.turno)
                    {
                        Session["reserva"] = "Reserva ya creada el dia " + reser2.dia + " en el turno " + reser2.turno;
                        return View(reser2);
                    }
                }

            }


            int sal = idSala(collection["Sala"]);
            try
            {

                string postdata = "{\"id_reserva\":\"" + collection["id_reserva"] + "\",\"id_sala\":\"" + sal + "\",\"dia\":\"" + collection["Dia"] + "\",\"turno\":\"" + collection["Turno"] + "\",\"observacion\":\"" + collection["observacion"] + "\"}";

                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(resRESTService);
                req.Method = "PUT";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }


    }
}
